/*
** file_utils.c for file_utils in /home/vermel/local/epitech/tek2/c/ftrace/pullup-project/sources
** 
** Made by nathan vermelle
** Login   <vermel_n@epitech.net>
** 
** Started on  Sun Jul  1 17:37:34 2012 nathan vermelle
** Last update Sun Jul  1 17:37:40 2012 nathan vermelle
*/

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>

static int	get_file(int pid)
{
  char	*tmp;
  int	res;

  if (pid < 0 || pid > 99999)
    return (-1);
  tmp = malloc(20);
  sprintf(tmp, "/proc/%d/exe", pid);
  res = open(tmp, O_RDONLY);
  free(tmp);
  return (res);
}

void	*load_file(int pid, int *s)
{
  int		fd;
  struct stat	fs;
  void		*res;

  if ((fd = get_file(pid)) < 0 || fstat(fd, &fs) < 0 ||
      (res = mmap(NULL, fs.st_size, PROT_READ, MAP_PRIVATE, fd, 0))
      == MAP_FAILED)
    return (NULL);
  close(fd);
  *s = fs.st_size;
  return (res);
}
